package top.chukongxiang.dubboboot.simple.common.utils;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;

/**
 * spring-boot 接口工具类
 * @author 楚孔响
 * @version 1.0
 * @date 2021/6/27 22:48
 */
public class ApiUtils {

    public static String getApiUrl(Class<?> clazz, String methodName) {

        // 获取class上的@RequestMapping注解
        String classUrl = getRequestAnnotationValue(clazz);
        StringBuilder sb = null;
        if (classUrl == null) {
            return null;
        } else {
            sb = new StringBuilder(classUrl);
            sb.append("/");
        }

        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                String methodUrl = getRequestAnnotationValue(method);
                if (methodUrl != null) {
                    sb.append(methodUrl);
                }
            }
        }

        return sb.toString().replaceAll("//", "/");
    }

    public static String getRequestAnnotationValue(Class<?> clazz) {
        String value;
        RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
        if (requestMapping == null || requestMapping.value().length == 0) {
            PostMapping postMapping = clazz.getAnnotation(PostMapping.class);
            if (postMapping == null || postMapping.value().length == 0) {
                GetMapping getMapping = clazz.getAnnotation(GetMapping.class);
                if (getMapping == null || getMapping.value().length == 0) {
                    return null;
                } else {
                    value = getMapping.value()[0];
                }
            } else {
                value = postMapping.value()[0];
            }
        } else {
            value = requestMapping.value()[0];
        }
        return value;
    }
    public static String getRequestAnnotationValue(Method method) {
        String value;
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
        if (requestMapping == null || requestMapping.value().length == 0) {
            PostMapping postMapping = method.getAnnotation(PostMapping.class);
            if (postMapping == null || postMapping.value().length == 0) {
                GetMapping getMapping = method.getAnnotation(GetMapping.class);
                if (getMapping == null || getMapping.value().length == 0) {
                    return null;
                } else {
                    value = getMapping.value()[0];
                }
            } else {
                value = postMapping.value()[0];
            }
        } else {
            value = requestMapping.value()[0];
        }
        return value;
    }

}
